package com.test.cordova.service;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;


import com.test.cordova.util.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *服务启动管理
 */

public class ServiceManager {

    private static final String TAG = ServiceManager.class.getSimpleName();
    private ServiceManager(){}
    private Map<Class,Intent> services = new HashMap<>();
    private static ServiceManager instance = new ServiceManager();

    public static ServiceManager getInstance() {
        return instance;
    }

    /**
     * 启动服务
     * @param activity
     * @param serviceClass
     * @param params
     */
    public void startService(Activity activity, Class serviceClass,Map<String, String> params){
        Intent it = new Intent(activity, serviceClass);
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                it.putExtra(key,params.get(key));
            }
        }
        if (!isServiceWork(activity, serviceClass.getName())) {
            Logger.i(TAG, "服务不在，重新开启服务");
        }else {
            Logger.i(TAG, "服务还在,重启服务");
            activity.stopService(it);
        }
        services.put(serviceClass,it);
        activity.startService(it);
    }


    /**
     * 停止服务
     * @param activity
     * @param serviceClass
     */
    public void stopService(Activity activity, Class serviceClass){
        Intent intent = services.get(serviceClass);
        if (intent != null) {
            activity.stopService(intent);
            services.remove(serviceClass);
        }
    }

    /**
     *  是否启动过指定服务
     *  仅限通过ServiceManager startService启动的服务
     * @param serviceClass
     * @return
     */
    public boolean isStart(Class serviceClass){
        return services.containsKey(serviceClass);
    }


    /**
     * bind 启动服务
     * 自己处理 ServiceConnection
     * @param activity
     * @param cls
     * @param params
     */
    public void bindService(Activity activity, Class cls,Map<String, String> params){
        Intent it = new Intent(activity, cls);
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                it.putExtra(key,params.get(key));
            }
        }
        if (!isServiceWork(activity, cls.getName())) {
            Logger.i(TAG, "服务不在，重新开启服务");
        }else {
            Logger.i(TAG, "服务还在,重启服务");
            activity.stopService(it);
        }
        services.put(cls,it);
        activity.bindService(it,locationPermission, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection locationPermission = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param mContext
     * @param serviceName 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

}
